﻿// ***********************************************************************
// Assembly         : MVC4Portal
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="Global.asax.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using InnovaApp.Layers.CommonLayer.Controllers.ViewControllers.LayoutViewControllers;
using InnovaApp.Portals.MVC4Portal.App_Start;
using INNOVACALL.Framework.Common.Logging;
using INNOVACALL.Framework.Common.Extensions;
using InnovaApp.Layers.ResourcesLayer.Properties;
using System.Globalization;
using System.Threading;
using InnovaApp.Portals.MVC4Portal.Controllers;

namespace InnovaApp.Portals.MVC4Portal
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    /// <summary>
    /// Class MvcApplication
    /// </summary>
    public class MvcApplication : System.Web.HttpApplication
    {
        private string eMethodBase = "InnovaApp.Portals.MVC4Portal.MvcApplication";
        /// <summary>
        /// Application start handler
        /// Warning : if you run this under IIS, this event occurs when application pool is restarted or recycled or when you restart the website
        /// </summary>
        protected void Application_Start()
        {
            PortalEnvironment.Refresh();

            AreaRegistration.RegisterAllAreas();

            //Warning : Call order is important
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Logger logger = new Logger();
        }

        //void Application_Error(object sender, EventArgs e)
        //{
        //    Response.Clear();
        //    if (RequestIsAjax())
        //    {
        //        Response.ContentType = "application/json";
        //    }
        //    else
        //    {
        //        Response.Redirect("Your error page URL here");
        //    }
        //    Server.ClearError();
        //}        

        //protected void Application_AcquireRequestState(object sender, EventArgs e)
        //{

        //    var handler = Context.Handler as MvcHandler;
        //    var routeData = handler != null ? handler.RequestContext.RouteData : null;
        //    var routeCulture = (routeData != null ? (routeData.Values["language"] != null ? routeData.Values["language"].ToString() : null) : null);
        //    var languageCookie = HttpContext.Current.Request.Cookies[INNOVACALL.Framework.Common.MVCHelpers.Localization.CommonLocalization.FavoriteLanguageCookieName];
        //    var userLanguages = HttpContext.Current.Request.UserLanguages;

        //    // Set the Culture based on a route, a cookie or the browser settings,
        //    // or default value if something went wrong
        //    var cultureInfo = new CultureInfo(
        //        routeCulture ?? (languageCookie != null
        //           ? languageCookie.Value
        //           : userLanguages != null
        //               ? userLanguages[0]
        //               : InnovaApp.Layers.CommonLayer.Controllers.Environment.DefaultLanguage)
        //    );

        //    INNOVACALL.Framework.Common.MVCHelpers.Localization.CommonLocalization.SetCurrentThreadLanguage(cultureInfo.IetfLanguageTag);
        //}


        /// <summary>
        /// Application begin request handler
        /// </summary>
        //protected void Application_BeginRequest()
        //{
        //    var s = Request.HttpMethod;
        //}


        /// <summary>
        /// Application end request handler
        /// </summary>
        //protected void Application_EndRequest(object sender, EventArgs e)
        //{
        //    string eMethod = eMethodBase + ".Application_EndRequest";
        //    if (
        //        Context.Response.StatusCode >= 400
        //        )
        //    {
        //        var context = new HttpContextWrapper(Context);
        //        if (!context.Request.IsAjaxRequest())
        //        {
        //            Logger.Info(enLog.Technical, "Error during normal request for " + Request.Url);
        //            string[] tLanguages = InnovaApp.Layers.CommonLayer.Controllers.Environment.Languages.Split(',');
        //            string[] tUserLanguages = HttpContext.Current.Request.UserLanguages;
        //            string[] tUserLanguagesAllowed = tLanguages.Intersect(tUserLanguages.Select(x => x.ToLower())).ToArray();
        //            string language = InnovaApp.Layers.CommonLayer.Controllers.Environment.DefaultLanguage;

        //            if (tUserLanguagesAllowed.Length > 0)
        //            {
        //                language = tUserLanguages[0];
        //            }
        //            language = language.ToLower();
        //            Exception exception = Server.GetLastError();
        //            INNOVACALL.Framework.Common.InnovacallExceptions.I_InnovacallExceptions_Base InnoEx;
        //            if (exception == null)
        //            {
        //                InnoEx = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, null, Resources.View_HttpError_500);
        //                InnoEx.LogIt();
        //            }
        //            else if (typeof(INNOVACALL.Framework.Common.InnovacallExceptions.I_InnovacallExceptions_Base).IsAssignableFrom(exception.GetType()))
        //            {
        //                InnoEx = (INNOVACALL.Framework.Common.InnovacallExceptions.I_InnovacallExceptions_Base)exception;
        //                InnoEx.LogIt();
        //            }
        //            else
        //            {
        //                InnoEx = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, null, exception.Message);
        //                InnoEx.LogIt();
        //            }
        //            Server.ClearError();
        //            Response.Clear();
        //            var routeData = new RouteData();

        //            routeData.Values["friendlyUrl"] = language + "/Error/" + Context.Response.StatusCode;
        //            routeData.Values["controller"] = "Error";
        //            routeData.Values["action"] = "Index";
        //            routeData.Values["errorCode"] = Context.Response.StatusCode.ToString();
        //            routeData.Values["language"] = language;
        //            routeData.Values["exception"] = exception;

        //            IController c = new ErrorController();
        //            c.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        //        }
        //    }
        //}
        /// <summary>
        /// Session start handler
        /// </summary>
        protected void Session_Start()
        {
            Logger.Debug(enLog.Business, string.Format(@"Session started with Id : {0}", Session.SessionID));
        }
        /// <summary>
        /// Returns true if request is an ajax one
        /// </summary>
        /// <returns></returns>
        private bool RequestIsAjax()
        {
            //The easy way
            bool toReturn = (Request["X-Requested-With"] == "XMLHttpRequest")
            || ((Request.Headers != null)
            && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

            if (!toReturn)
            {
                try
                {
                    //The controller and action
                    string controllerName = Request.RequestContext.
                                            RouteData.Values["controller"].ToString();
                    string actionName = Request.RequestContext.
                                        RouteData.Values["action"].ToString();

                    //We create a controller instance
                    DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
                    Controller controller = controllerFactory.CreateController(
                    Request.RequestContext, controllerName) as Controller;

                    //We get the controller actions
                    ReflectedControllerDescriptor controllerDescriptor =
                    new ReflectedControllerDescriptor(controller.GetType());
                    ActionDescriptor[] controllerActions =
                    controllerDescriptor.GetCanonicalActions();

                    //We search for our action
                    foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
                    {
                        if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
                        {
                            //If the action returns JsonResult then we have an AJAX request
                            if (actionDescriptor.MethodInfo.ReturnType
                            .Equals(typeof(JsonResult)))
                                return true;
                        }
                    }
                }
                catch
                {

                }
            }

            return toReturn;
        }

    }
}